﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using StevensReceipts.Domain;

namespace StevensReceipts.Repository
{
    public class Repository<T> : IRepository<T> where T : class, IEntity //where C : DbContext, new()
    {
        ////private C _context;

        ////public Repository()
        ////{
        ////    _context = new C();
        ////} 

        private ReceiptsDbContext _context;

        public Repository(ReceiptsDbContext receiptsDb)
        {
            _context = receiptsDb;
        } 
        private IDbSet<T> DbSet
        {
            get { return _context.Set<T>(); }
        } 

        #region Implementation of IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected  virtual  void Dispose(bool disposing)
        {
            if(disposing)
            {
                if(_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }

        #endregion

        #region Implementation of IRepository<T>

        public IQueryable<T> GetAll()
        {
            return DbSet.AsQueryable();
        }

        public T GetSingle(Expression<Func<T, bool>> predicate)
        {
            return DbSet.Where(predicate).SingleOrDefault();
            //return DbSet.SingleOrDefault(t => t.Id == Id);
        }

        public IQueryable<T> Get(Expression<Func<T, bool>> predicate)
        {
            return DbSet.Where(predicate);
        }

        //public T GetById(int id)
        //{
        //    return DbSet.SingleOrDefault(t => t.Id == id);
        //}

        public T Add(T entity)
        {
            return DbSet.Add(entity);
        }

        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }


        public void Update(T entity)
        {
            _context.Entry(entity).State = EntityState.Modified;
        }
        #endregion
    }
}